package com.atom.app.mvi.net.interceptor

import com.atom.app.mvi.Contacts
import com.tencent.mmkv.MMKV
import okhttp3.Interceptor
import okhttp3.Response

class SessionInterceptor : Interceptor {
    val mmkv: MMKV = MMKV.defaultMMKV()

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val path = request.url.toUrl().path
        val builder = request.newBuilder()
        if (!path.contains("login")) {
            val session = mmkv.decodeString(Contacts.net_session) ?: ""
            val username = mmkv.decodeString(Contacts.net_username) ?: ""
            builder.addHeader("Cookie", "username=${username}; sessionid=${session}").build()
        }
        if (path.contains("login")) {
            val response = chain.proceed(builder.build())
            response.headers.forEach {
                if (it.first == "Set-Cookie") {
                    val splits = it.second.split(";")
                    splits.forEach { split ->
                        val split1 = split.split("=")
                        if (split1.size == 2) {
                            if (split1[0] == "username") {
                                mmkv.encode(Contacts.net_username, split1[0])
                            }
                            if (split1[0] == "sessionid") {
                                mmkv.encode(Contacts.net_session, split1[0])
                            }
                        }
                    }
                }
            }
            return response
        }
        return chain.proceed(builder.build())
    }
}
